package com.qili.service.it.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.base.BaseDict;
import com.qili.entity.base.Col;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.sys.SysLog;
import com.qili.mapper.search.ItFormMapper;
import com.qili.mapper.supervisor.SupervisorFileMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.SupervisorProjectFormsService;
import com.qili.util.BeanUtil;
import com.qili.util.CommonUtil;
import com.qili.util.DateUtil;
import com.qili.util.ReType;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @date 2020/11/3
 * @description     专利表单具体业务类
 */
@Log
@Service("ZhuanliFormService")
public class ZhuanliFormServiceImpl extends FormBaseServiceImpl{

    private static final Integer FILE_COUNT = 6;

    @Autowired
    ItFormMapper itFormMapper;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;

    @Autowired
    SysLogMapper sysLogMapper;

    @Autowired
    private SupervisorFileMapper supervisorFileMapper;

    public void saveFormData(SupervisorProjectFromsDTO forms, boolean ifNew) {
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //把原来的删除:
            SupervisorProjectFormsData formsData = new SupervisorProjectFormsData();
            formsData.setSpfId(forms.getSpfId());
            formsDataService.delete(formsData);
        }
        //发明人
        SupervisorProjectFormsData spfd=new SupervisorProjectFormsData();
        ArrayList<String> strList1 = forms.getStrList1();
        if(CollectionUtil.isNotEmpty(strList1)){
            for(int i=0;i<strList1.size();i++){
                spfd.setSpfdataId(IdUtil.simpleUUID());
                spfd.setSpfId(forms.getSpfId());
                spfd.setData1(strList1.get(i));
                spfd.setTableIndex(i);
                spfd.setData10("famingren");
                formsDataService.insertSelective(spfd);
            }
        }

        //年费信息:
        ArrayList<SupervisorProjectFormsData> formDataList = forms.getFormDataList();
        if(CollectionUtil.isNotEmpty(formDataList)){
            for(int i=0;i<formDataList.size();i++){
                SupervisorProjectFormsData formsData = formDataList.get(i);
                if(StringUtils.isBlank(formsData.getData2()) && StringUtils.isBlank(formsData.getData3())
                        && StringUtils.isBlank(formsData.getData4()) && StringUtils.isBlank(formsData.getData5())){
                    continue;
                }
                formsData.setSpfdataId(IdUtil.simpleUUID());
                formsData.setSpfId(forms.getSpfId());
                formsData.setTableIndex(i);
                formsData.setData10("nianfeixinxi");
                formsDataService.insertSelective(formsData);
            }
        }
    }

    /**
     * 保存表单文件
     * @param forms
     * @param ifNew
     */
    public void saveFormFile(SupervisorProjectFromsDTO forms, boolean ifNew) {
        ArrayList<String> fileIds = new ArrayList<String>();
        //技术交底书
        ArrayList<String> jiShuJiaoDiFileIds = forms.getStrList2();
        //权利要求书
        ArrayList<String> QuanLiYaoQiuFileIds = forms.getStrList3();
        //专利检索报告
        ArrayList<String> JianSuoBaoGaoFileIds = forms.getStrList4();
        //递交信息确认表
        ArrayList<String> DiJiaoXinXiFileIds = forms.getStrList5();
        //专利受理书
        ArrayList<String> ShouLiFileIds = forms.getStrList6();
        //专利授权书
        ArrayList<String> ShouQuanFileIds = forms.getStrList7();
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //编辑表单页面不需要移动文件，只是操作删除数组:
            ArrayList<String> strList9 = forms.getStrList9();
            if(CollectionUtil.isNotEmpty(strList9)){
                for(String delFileId:strList9){
                    //设置为回收站状态:
                    SupervisorFile delFile = new SupervisorFile();
                    delFile.setId(delFileId);
                    delFile.setDeleteState("2");
                    delFile.setDeleteUser(CommonUtil.getUserId());
                    delFile.setDeleteDate(DateUtil.getCurrentDateString());
                    dicService.updateByPrimaryKeySelective(delFile);
                    SupervisorFile supervisorFile = supervisorFileMapper.selectByPrimaryKey(delFileId);
                    if(supervisorFile!=null){
                        insertFileLog(supervisorFile.getFileName());
                    }
                }
            }
        }else{
            //合并:
            if(CollectionUtil.isNotEmpty(jiShuJiaoDiFileIds)){
                fileIds.addAll(jiShuJiaoDiFileIds);
            }
            if(CollectionUtil.isNotEmpty(QuanLiYaoQiuFileIds)){
                fileIds.addAll(QuanLiYaoQiuFileIds);
            }
            if(CollectionUtil.isNotEmpty(JianSuoBaoGaoFileIds)){
                fileIds.addAll(JianSuoBaoGaoFileIds);
            }
            if(CollectionUtil.isNotEmpty(DiJiaoXinXiFileIds)){
                fileIds.addAll(DiJiaoXinXiFileIds);
            }
            if(CollectionUtil.isNotEmpty(ShouLiFileIds)){
                fileIds.addAll(ShouLiFileIds);
            }
            if(CollectionUtil.isNotEmpty(ShouQuanFileIds)){
                fileIds.addAll(ShouQuanFileIds);
            }
            //这里是新建表单逻辑:
            //新建表单核心文件夹:
            String formCode = forms.getSpfF30();
            FormType formType = FormType.getFormType(formCode);
            //生成表单核心文件夹路径：（例如:/书著/2021_001_xx书著）
            //该方法执行后,会把核心文件设置为formDto的Obj1对象
            createCenterDic(forms);
            SupervisorFile centFile = (SupervisorFile) forms.getObj1();
            if(CollectionUtil.isNotEmpty(fileIds)){
                //这里面存放的是临时文件id:
                for(String shuzhuFileId : fileIds){
                    SupervisorFileTemp supervisorFileTemp = fileTempService.selectByPrimaryKey(shuzhuFileId);
                    //1.移动操作系统文件 newFile为移动后的文件
                    File newFile = moveTempFile(supervisorFileTemp, forms);
                    //2.复制数据到正式文件表
                    //更改url
                    supervisorFileTemp.setUrl(newFile.getPath());
                    SupervisorFile newSupervisorFile = new SupervisorFile();
                    BeanUtil.copyNotNullBean(supervisorFileTemp,newSupervisorFile);
                    newSupervisorFile.setZskfileType("2");
                    newSupervisorFile.setDeleteState("1");
                    //表单中的每一个文件都指向该核心文件
                    newSupervisorFile.setLinkId(centFile.getId());
                    fileService.insertFile(newSupervisorFile,(SupervisorFile) forms.getObj1());
                    //3.删除临时文件表
                    fileTempService.deleteByPrimaryKey(shuzhuFileId);
                }
            }
        }
    }

    public void insertFileLog(String filename) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("DEL");
        sysLog.setText("删除文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser user = CommonUtil.getUser();
        sysLog.setUserName(user.getUsername());
        sysLogMapper.insert(sysLog);
    }


    /**
     * 获取表单数据
     * @param formTypeCode
     * @param formDto
     * @param model
     */
    public void getFormData(String formTypeCode, SupervisorProjectFromsDTO formDto, Model model) {
        Example famingrenExample = new Example(SupervisorProjectFormsData.class);
        famingrenExample.and().andEqualTo("data10","famingren")
                .andEqualTo("spfId",formDto.getSpfId());
        famingrenExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select1 = formsDataService.selectByExample(famingrenExample);
        if(CollectionUtil.isNotEmpty(select1)){
            select1.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
            if(model != null){
                model.addAttribute("famingrens",select1);
            }else{
                formDto.setObj1(select1);
            }

        }

        Example nianfeiExample = new Example(SupervisorProjectFormsData.class);
        nianfeiExample.and().andEqualTo("data10","nianfeixinxi")
                .andEqualTo("spfId",formDto.getSpfId());
        nianfeiExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select2 = formsDataService.selectByExample(nianfeiExample);
        if(CollectionUtil.isNotEmpty(select2)){
            select2.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
            if(model != null){
                model.addAttribute("nianfeixinxis", JSON.toJSONString(select2));
            }else{
                formDto.setObj2(select2);
            }
        }
    }

    public ReType selectFormBook(SupervisorProjectFromsDTO formInfo, String page, String limit) {
        Map paraMap = new HashMap();
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            paraMap.put("spfF1","%"+formInfo.getSpfF1()+"%");
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF2()) && !"000".equals(formInfo.getSpfF2())){
            paraMap.put("spfF2",formInfo.getSpfF2());
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF3()) && !"000".equals(formInfo.getSpfF3())){
            paraMap.put("spfF3",formInfo.getSpfF3());
        }
        if(formInfo.getObj5()!= null){
            if(StringUtils.isNotBlank(formInfo.getObj5().toString())){
                paraMap.put("obj5",formInfo.getObj5().toString().trim());
            }
        }
        if(formInfo.getObj6()!= null){
            if(StringUtils.isNotBlank(formInfo.getObj6().toString())){
                paraMap.put("obj6",formInfo.getObj6().toString().trim());
            }
        }
        if(formInfo.getObj1()!= null){
            if(StringUtils.isNotBlank(formInfo.getObj1().toString())){
                paraMap.put("obj1",formInfo.getObj1().toString());
            }
        }
        if(formInfo.getObj2()!= null){
            if(StringUtils.isNotBlank(formInfo.getObj2().toString())){
                paraMap.put("obj2",formInfo.getObj2().toString());
            }
        }
        if(formInfo.getObj3()!= null){
            if(StringUtils.isNotBlank(formInfo.getObj3().toString())){
                paraMap.put("obj3",formInfo.getObj3().toString());
            }
        }
        if(formInfo.getObj4()!= null){
            if(StringUtils.isNotBlank(formInfo.getObj4().toString())){
                paraMap.put("obj4",formInfo.getObj4().toString());
            }
        }
        Page<SupervisorProjectFromsDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupervisorProjectForms> supervisorProjectForms = itFormMapper.selectZLTZ(paraMap);
        List<SupervisorProjectFromsDTO> formDto = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(supervisorProjectForms)){
            formDto = getFormDto(formInfo.getSpfF30(), supervisorProjectForms);

        }
        return new ReType(tPage.getTotal(),formDto);
    }

    private List<SupervisorProjectFromsDTO> getFormDto(String formTypeCode,List<SupervisorProjectForms> supervisorProjectForms) {
        List<SupervisorProjectFromsDTO> formsDtoList = new ArrayList<SupervisorProjectFromsDTO>();
        for(int i=0;i<supervisorProjectForms.size();i++){
            SupervisorProjectForms aForm = supervisorProjectForms.get(i);
            SupervisorProjectFromsDTO aDto = changeToDto(aForm);
            getFormData(formTypeCode,aDto,null);
            setFormFiles(formTypeCode,aDto);
            aDto.setFileInd(i+1);
            formsDtoList.add(aDto);
        }
        return formsDtoList;
    }

    /**
     * 获取专利统计表格数据:
     *
     *  //姓名
     * 		var name = $('#name').val();
     * 		var qlyqsName = $('#qlyqs_name').val();
     * 		//日期类型 1:授权时间  2:受理时间
     * 		var timeType = $('#time_type'+defaultTabInd).val();
     * 		var start = $('#date_start'+defaultTabInd).val();
     * 		var end = $('#date_end'+defaultTabInd).val();
     * 		var jsondata = {
     * 			obj1:name,
     * 			spfF8:qlyqsName
     *                };
     * 		if(timeType == '1'){
     * 			jsondata['obj2'] = start;
     * 			jsondata['obj3'] = end;
     *        }else if(timeType == '2'){
     * 			jsondata['obj4'] = start;
     * 			jsondata['obj5'] = end;
     *        }
     * 		return jsondata;
     * @return
     */
    @Override
    public ReType selectFormStatisticsTableData(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index, String page, String limit) {
        if(StringUtils.isNotBlank(index)){
            if("1".equals(index)){
                if(null != formInfo.getSpfF8() && StringUtils.isNotBlank(formInfo.getSpfF8().toString())){
                    formInfo.setSpfF8(formInfo.getSpfF8().toString().trim());
                }
            }
        }
        Map paraMap = new HashMap();
        //查询所有的发明类型:
        BaseDict select = new BaseDict();
        select.setBadtTypecode("ZLLX001");
        List<BaseDict> select1 = baseDictService.select(select);
        if(CollectionUtil.isNotEmpty(select1)){
            paraMap.put("zllxList",select1);
        }
        if("0".equals(index)){
            //先根据条件,获取发明人下标集合
            List<String> tableIndexList = getFamingrenIndexListTj(formInfo);
            if(CollectionUtil.isNotEmpty(tableIndexList)){
                List<String> famingrenLevelList = new ArrayList<>();
                for(int i=0;i<tableIndexList.size();i++){
                    if(i > 7){
                        paraMap.put("otherFamingren","1");
                        break;
                    }
                    famingrenLevelList.add(tableIndexList.get(i)+"");
                }
                paraMap.put("famingrenLevelList",famingrenLevelList);
            }
            paraMap.put("obj1",formInfo.getObj1());
            paraMap.put("obj2",formInfo.getObj2());
            paraMap.put("obj3",formInfo.getObj3());
            paraMap.put("obj4",formInfo.getObj4());
            paraMap.put("obj5",formInfo.getObj5());

            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getZhuanLiStatistics0(paraMap);
            //获取根据符合条件的年份列表:

            return new ReType(objects.getTotal(),resultMap);
        }else if("1".equals(index)){
            //spfF8:权利要求书名称     obj2:授权时间开始时间       obj3:授权时间结束时间       obj4:受理时间开始时间       obj5:受理时间结束时间
            paraMap.put("spfF8",formInfo.getSpfF8()!=null?formInfo.getSpfF8():"");
            paraMap.put("obj2",formInfo.getObj2()!=null?formInfo.getObj2().toString():"");
            paraMap.put("obj3",formInfo.getObj3()!=null?formInfo.getObj3().toString():"");
            paraMap.put("obj4",formInfo.getObj4()!=null?formInfo.getObj4().toString():"");
            paraMap.put("obj5",formInfo.getObj5()!=null?formInfo.getObj5().toString():"");
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getZhuanLiStatistics1(paraMap);
            //获取根据符合条件的年份列表:

            return new ReType(objects.getTotal(),resultMap);
        }else if("2".equals(index)){
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getZhuanLiStatistics2(paraMap);
            //获取根据符合条件的年份列表:
            return new ReType(objects.getTotal(),resultMap);
        }
        return null;
    }


    /**
     * 获取统计表格表头
     * @param formTypeCode
     * @param formInfo
     * @param index
     * var jsondata = {
     * 			spfF1:lwmc,
     * 			spfF2:author,
     * 			spfF5:projectName,
     * 			spfF8:jkrqStart,
     * 			spfF9:jkrqEnd
     *                };
     * @return
     */
    @Override
    public List<Col> getFormStatisticstableHead(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index) {
        if(StringUtils.isBlank(index)){
            return null;
        }
        List<Col> colArrayList = new ArrayList<>();
        //查询所有的发明类型:
        BaseDict select = new BaseDict();
        select.setBadtTypecode("ZLLX001");
        List<BaseDict> select1 = baseDictService.select(select);
        if("0".equals(index)) {
            //按照人统计情况:
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //姓名:
            colArrayList.add(new Col("famingren","姓名","10%",null,null,null,false));
            //总篇数:
            colArrayList.add(new Col("totalCount","总篇数","10%",null,
                    "color: dodgerblue;cursor: pointer","showCountDetail",false));
            //根据条件获取发明人数:
            List<String> famingrenIndexListTj = getFamingrenIndexListTj(formInfo);
            if(CollectionUtil.isNotEmpty(famingrenIndexListTj)){
                for(int i=0;i<famingrenIndexListTj.size();i++){
                    if(i > 7){
                        colArrayList.add(new Col("otherFaMingRen","其他发明人数","10%",null,null,null,false));
                        break;
                    }
                    String tableIndex = famingrenIndexListTj.get(i);
                    //第 n 作者数:
                    colArrayList.add(new Col(tableIndex+"","第"+(Integer.valueOf(tableIndex)+1)+"发明人数","10%",null,null,null,false));
                }
            }

            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict aZllx : select1){
                    //每个专利类型:
                    colArrayList.add(new Col(aZllx.getBadtCode(),aZllx.getBadtName()+"数","10%",null,null,null,false));
                }
            }
        }else if("1".equals(index)) {
            //按照权利要求书情况:
            //序号:
            colArrayList.add(new Col(null,"序号","20%","#index",null,null,false));
            //总篇数:
            colArrayList.add(new Col("totalCount","总篇数","20%",null,null,null,false));
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict aZllx : select1){
                    //每个期刊类型:
                    colArrayList.add(new Col(aZllx.getBadtCode(),aZllx.getBadtName(),"20%",null,null,null,false));
                }
            }
        }else if("2".equals(index)) {
            //按照时间统计
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //年份:
            colArrayList.add(new Col("year","年份","10%",null,null,null,false));
            //论文总篇数:
            colArrayList.add(new Col("totalCount","专利总篇数","20%",null,null,null,false));
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict azllx : select1){
                    //每个期刊类型:
                    colArrayList.add(new Col(azllx.getBadtCode(),azllx.getBadtName(),"20%",null,null,null,false));
                }
            }
        }
        return colArrayList;
    }


    /**
     * 统计时,根据条件,查询符合条件的作者最大数:
     * @param formInfo
     * var jsondata = {
     * 			spfF1:lwmc,
     * 			spfF2:author,
     * 			spfF5:projectName,
     * 			spfF8:jkrqStart,
     * 			spfF9:jkrqEnd
     *                };
     * @return
     */
    public List<String> getFamingrenIndexListTj(SupervisorProjectFromsDTO formInfo) {
        if(null != formInfo.getObj1() && StringUtils.isNotBlank(formInfo.getObj1().toString())){
            formInfo.setObj1(formInfo.getObj1().toString().trim());
        }

        List<String> authorIndexListTj = itFormMapper.getFaMingRenIndexListTj(formInfo);
        return authorIndexListTj;
    }


}
